<?php
namespace Admin\Controller;
class LoginController extends CommonController {
    public function index(){
        if(IS_POST){
            $this->_Login_Submit();
            exit;
        }
        $this->display('index');
    }

    public function _Login_Submit(){
        /*
         *  登陆状态说明
         * 0 验证码错误
         * 1 账号或密码必填
         * 2 账号或密码错误
         * 3 登陆成功
         * */
        $username = I('post.username');
        $password = I('post.password');
        $code = I('post.code');

        $Return = array();
        $stop = 0; // 有错误就终止下下的代码继续判断
        $verify = new \Think\Verify();
        if(empty($code) || $verify->check($code) == false){
            $stop = 1;
            $Return['msg'] = '验证码错误';
            $Return['code'] = 0;
        }

        if($stop != 1 && empty($username) || empty($password)){
            $stop = 1;
            $Return['msg'] = '账号或密码为空';
            $Return['code'] = 1;
        }

        $password = md5($password . C("LoginPassword_Key"));
         $Table = M('administrator');

       if($stop != 1){
           $where = array(
               'username' => $username,
           );

           $result = $Table->where($where)->find();
       }

        // 账号密码验证区
        if($stop != 1 && $result['username'] != '') {
            if ($result['password'] == $password) {
                // 登陆成功
                $Return['code'] = 3;
                $Return['msg'] = '登陆成功';

                session('Admin_Id', $result['id']);
                session('Admin_username', $result['username']);
                session('Admin_nickname', $result['nickname']);
            }else{
                // 密码错误
                $Return['msg'] = '密码错误';
                $Return['code'] = 2;
            }
        }elseif($stop != 1){
            $Return['msg'] = '用户名或密码错误';
            $Return['code'] = 2;
        }

        $this->ajaxReturn($Return,'json'); // 返回最终结果
    }

    public function Login_Code(){
        // 登陆验证码
        $config =    array(
            'fontSize'    =>    15,    // 验证码字体大小
            'length'      =>    4,     // 验证码位数
            'useNoise'    =>    false, // 关闭验证码杂点
        );
        $Verify =     new \Think\Verify($config);
        $Verify->entry();
    }

    public function Logout(){
        $id = session('Admin_Id');
        if(isset($id)) {
            unset($_SESSION['Admin_Id']);
            unset($_SESSION['Admin_username']);
            unset($_SESSION['Admin_nickname']);
            $this->redirect('index');
        }else{
            $this->error('退出失败');
        }
    }
}